package com.dayuanit.dy15.atm.servlet;

import com.dayuanit.dy15.atm.dto.ResponseDTO;
import com.dayuanit.dy15.atm.entity.User;
import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.service.UserService;
import com.dayuanit.dy15.atm.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        try {
            if ("register".equals(action)) {
                register(req, resp);
            }

            if ("login".equals(action)) {
                login(req, resp);
            }

            if ("logout".equals(action)) {
                logout(req, resp);
            }
        } catch (BizException be) {
            be.printStackTrace();
            responseByAjax(ResponseDTO.fail(be.getMessage()), resp);
        } catch (Exception e) {
            e.printStackTrace();
            responseByAjax(ResponseDTO.fail("系统异常，请联系客服"), resp);
        }
    }

    /**
     * 退出的本质：就是让系统不认你，只需要将session里的内容清理掉，然后再将session置为失效即可。
     * @param req
     * @param resp
     * @throws Exception
     */
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        session.removeAttribute("loginUser");
        //将session置为失效
        session.invalidate();

        resp.sendRedirect("/toPage?pageName=login");
    }

    /**
     * 登录的本质：就是告诉系统你是谁。专业术语：登录即使认证。
     * 认证的方式有很多，常见的就是用户名+密码的方式
     * 现在还有很多认证的方式：比如,faceId，指纹，滴血，第三方认证
     * @param req
     * @param resp
     * @throws Exception
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userService.login(username, password);
        //request对象生命周期很短暂，跟当前请求的生命周期一致，当前结束，那么request和response对象也就结束
//        req.setAttribute("loginUser", user);

        HttpSession session = req.getSession();

        //true=如果能够通过jessionId找到session对象，那么就直接返回；反之，则创建新的session对象。
        //false=如果通过jessionId找到session对象，那么直接返回；反之，不创建新的session对象。
        //session对象并不是在你第一次访问站点时创建的，而是代码中有显示的调用getSession()方法才会创建对象；
        req.getSession(false);

        System.out.println("login sessionID=" + session.getId());
        session.setAttribute("loginUser", user);

        Cookie cookie = new Cookie("userToken", "iamok");
        Cookie cookie2 = new Cookie("passsToken", "123456");

        resp.addCookie(cookie);
        resp.addCookie(cookie2);

        System.out.println("user =" + session.getAttribute("loginUser"));
        responseByAjax(ResponseDTO.sucess(), resp);
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");

        userService.register(username, password, confirmPassword);

        responseByAjax(ResponseDTO.sucess(), resp);
    }
}
